package com.workshop.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.workshop.utils.ResultMsg;
import com.workshop.utils.session.SessionManager;

/**
 * 全局访问拦截器
 * @author chenluqiang
 * @date 2019年3月13日 上午10:04:18 
 *
 */
public class HandlerInterceperCustom implements HandlerInterceptor{
	
	private Logger logger = LoggerFactory.getLogger(HandlerInterceperCustom.class);
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		logger.info("——————进入———————— HandlerInterceperCustom ——————————————");
		response.setHeader("Access-Control-Allow-Origin", "*");// 允许所有域跨域请求
//		response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE,PUT");// 跨域请求的类型
		response.setHeader("Access-Control-Max-Age", "3600");// 跨域生命周期
//		response.setHeader("Access-Control-Allow-Headers", "x-requested-with");// 跨域数据响应方式
		response.setHeader("Access-Control-Allow-Headers", "userkey,x-requested-with");// 跨域数据响应方式
		// 前端配置了cookice证书的话Access-Control-Allow-Origin 不能设置为*
		response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
		// 前端配置cookice证书
		response.setHeader("Access-Control-Allow-Credentials", "true");
		//检查是否登录
		this.checkIsLogin(request);
		return true;
	}
	
	private void checkIsLogin(HttpServletRequest request) {
		String key = request.getHeader(ResultMsg.USERTOKEN);
		System.out.println("————————————————————key="+key);
		if(key!=null&&StringUtils.isNotBlank(key)) {
			SessionManager sessionManager = SessionManager.getInstance();
			HttpSession sess = sessionManager.getSession(key);
			if(sess!=null) {
				try {
					Object user =  sess.getAttribute("user");
					if(user!=null) {
						request.setAttribute(ResultMsg.USERTOKEN, user);
					}else {
						request.setAttribute(ResultMsg.USERTOKEN, null);
					}
				}catch(IllegalStateException e) {
					request.setAttribute(ResultMsg.USERTOKEN, null);
				}
			}else {
				request.setAttribute(ResultMsg.USERTOKEN, null);
			}
		}
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
	}
	// 响应后拦截1
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
	}
	
}
